<template>
  <div class="medicinePrescription-create">
    <div class="medicinePrescription-name">
      <div class="medicinePrescription-name-left" style="height: 60px">
        <el-form :model="submitData.prescription" ref="formName" label-width="80px">
          <el-form-item label="处方名称" prop="prescription_name"
                        :rules="{
            required: true,
            message: '请输入处方名称',
            trigger: 'blur'
          }">
            <el-input
              v-model="submitData.prescription.prescription_name"
              style="width: 400px"
              :disabled="detail=='1'"
              placeholder="请输入处方模板名称"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <!--      <div class="medicinePrescription-name-left">-->
      <!--        <p class="name">处方名称</p>-->
      <!--        <el-input-->
      <!--          v-model="submitData.prescription.prescription_name"-->
      <!--          class="name-input"-->
      <!--          :disabled="detail=='1'"-->
      <!--          placeholder="请输入处方模板名称"-->
      <!--        ></el-input>-->
      <!--      </div>-->
    </div>
    <div class="medicinePrescription-container" style="margin-top: -20px">
      <el-form
        :model="submitData.prescription"
        ref="patentMedicineValidateForm"
        label-width="100px"
        class="medicinePrescription-form"
        :disabled="detail=='1'"
      >
        <el-form-item class="form-item-header">
          <div class="top-header">
            <div class="top-left" style="display: flex;min-width: 1000px">
              <!--              <p>药品</p>-->
              <div style="min-width:60px">药品名称</div>
              <div style="margin-left: 286px;">用法</div>
              <div style="margin-left: 76px">用药频率</div>
              <div style="margin-left: 110px">单次剂量</div>
              <div style="margin-left: 150px">开药量</div>
            </div>
          </div>
        </el-form-item>
        <el-table
          row-class-name="table-row"
          :data="submitData.prescription.details"
          border
          style="width: 100%"
          :show-header="false"
        >
          <el-table-column label="药品名称" width="350px">
            <template slot-scope="scope">
              <el-autocomplete
                class="product-name-input"
                style="width: 350px"
                v-model="scope.row.product_name"
                :fetch-suggestions="cyQuerySearch"
                placeholder="请输入药品名称"
                :trigger-on-focus="false"
                @focus="addPatentItem(scope.$index)"
                @change="
                        (val) => {
                          cyChange(val, scope.$index, 'product');
                        }
                      "
                @select="
                  (item) => {
                    cyProHandleSelect(item, scope.$index);
                  }
              "
              >
                <template slot="suffix" v-if="scope.row.own ? false : true">
                  <el-tooltip
                    v-if="scope.row.product_name!==''"
                    content="该药品不在您的药库中或者库存不足，建议您更换其他药品"
                    placement="bottom"
                    effect="light"
                  >
                    <i class="el-icon-warning"> </i>
                  </el-tooltip>
                </template>
                <template slot-scope="{ item }">
                  <div
                    class="product-item-container"
                    style="
                            display: flex;
                            justify-content: flex-start;
                            align-items: flex-start;
                          "
                  >
                    <div class="icon-container" style="margin-right: 5px">
                      <i
                        class="el-icon-success"
                        style="color: green"
                        v-if="item.Own"
                      ></i>
                      <i class="el-icon-warning" v-else></i>
                    </div>
                    <div class="product-item" style="padding: 5px 0px">
                      <div
                        class="name"
                        style="font-weight: bold; line-height: 22px"
                      >
                              <span class="name-name">{{
                                item.product_name
                              }}</span
                              ><span class="name-pack">({{ item.pack }})</span>
                      </div>
                      <div
                        class="producer"
                        style="color: #999; line-height: 22px"
                      >
                        <span>{{ item.production }}</span>
                      </div>
                    </div>
                  </div>
                </template>
              </el-autocomplete>
            </template>
          </el-table-column>
          <el-table-column label="用法">
            <template slot-scope="scope">
              <el-autocomplete
                class="use-info-input"
                v-model="scope.row.use_way"
                :fetch-suggestions="cyyfQuerySearch"
                placeholder="用法"
                :trigger-on-focus="true"
                @select="
                      (val) => {
                        usageHandleSelect(val, scope.$index);
                      }
                    "
              >
                <template slot-scope="{ item }">
                  <div class="useage-item">
                    <div class="name">
                      <span>{{ item }}</span>
                    </div>
                  </div>
                </template>
              </el-autocomplete>
            </template>
          </el-table-column>
          <el-table-column label="用药频次">
            <template slot-scope="scope">
              <el-autocomplete
                class="frequency-input"
                v-model="scope.row.medication_rate"
                :fetch-suggestions="medicationRateQuerySearch"
                placeholder="用药频次"
                :trigger-on-focus="true"
                @select="
                      (val) => {
                        medicationRateHandleSelect(val, scope.$index);
                      }
                    "
              >
                <template slot-scope="{ item }">
                  <div class="useage-item">
                    <div class="name">
                      <span>{{ item }}</span>
                    </div>
                  </div>
                </template>
              </el-autocomplete>
            </template>
          </el-table-column>
          <el-table-column label="剂量">
            <template slot-scope="scope">
              <el-input
                class="num-input"
                v-model="scope.row.single_dose"
                placeholder="剂量"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="单位">
            <template slot-scope="scope">
              <el-autocomplete
                class="inline-input"
                v-model="scope.row.single_unit"
                :fetch-suggestions="singleUnitQuerySearch"
                placeholder="单位"
                :trigger-on-focus="true"
                @select="
                      (val) => {
                        singleUnitHandleSelect(val, scope.$index);
                      }
                    "
              >
                <template slot-scope="{ item }">
                  <div class="useage-item">
                    <div class="name">
                      <span>{{ item }}</span>
                    </div>
                  </div>
                </template>
              </el-autocomplete>
            </template>
          </el-table-column>
          <el-table-column label="数量">
            <template slot-scope="scope">
              <el-input
                class="num-input"
                v-model="scope.row.number"
                placeholder="数量"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="单位">
            <template slot-scope="scope">
              <el-autocomplete
                class="inline-input"
                v-model="scope.row.unit"
                :fetch-suggestions="numberUnitQuerySearch"
                placeholder="单位"
                :trigger-on-focus="true"
                @select="
                      (val) => {
                        numberUnitHandleSelect(val, scope.$index);
                      }
                    "
              >
                <template slot-scope="{ item }">
                  <div class="useage-item">
                    <div class="name">
                      <span>{{ item }}</span>
                    </div>
                  </div>
                </template>
              </el-autocomplete>
            </template>
          </el-table-column>
          <!--        <el-table-column label="数量">-->
          <!--          <template slot-scope="scope">-->
          <!--            <div>-->
          <!--              <el-autocomplete-->
          <!--                class="inline-input"-->
          <!--                v-model.number="scope.row.number"-->
          <!--                :fetch-suggestions="querySearch"-->
          <!--                placeholder="数量"-->
          <!--                :trigger-on-focus="false"-->
          <!--                @select="handleSelect"-->
          <!--              >-->
          <!--                <el-select-->
          <!--                  v-model="scope.row.unit"-->
          <!--                  slot="append"-->
          <!--                  placeholder="单位"-->
          <!--                >-->
          <!--                  <el-option label="盒" value="1"></el-option>-->
          <!--                  <el-option label="瓶" value="2"></el-option>-->
          <!--                  <el-option label="支" value="3"></el-option>-->
          <!--                </el-select>-->
          <!--              </el-autocomplete>-->
          <!--            </div>-->
          <!--          </template>-->
          <!--        </el-table-column>-->
          <el-table-column label="操作" width="30px" v-if="detail!='1'">
            <template slot-scope="scope">
              <div>
                <el-button
                  class="icon-btn"
                  icon="el-icon-delete"
                  @click.prevent="removePatentItem(scope.row)"
                ></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item class="form-item-btn">
          <div class="btn-container">
            <el-button type="text" @click.prevent="addPatentItem(-1)"
            >+新增药品
            </el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
  import {productSearch, productDetail} from "@/api/product.js";
  import publicRemind from "@/assets/js/publicRemind.js";

  export default {
    props: {
      editData: {
        type: Object,
        default: null,
      },
      detail: {
        type: String,
      }
    },
    data() {
      return {
        remindData: publicRemind.remind,
        submitData: {
          prescription: {
            prescription_name: "",
            category_key: "cycf",
            category_name: "成药处方",
            details: [
              {
                own:true,
                product_id: 0,
                product_name: "",
                pack: "", // 规格
                use_way: "", // 用法
                medication_rate: "", // 用药频率
                single_dose: "", // 用药频率
                single_unit: "", // 单次剂量
                number: "", // 数量
                price: 0, // 价格
                amount: 0, // 总价
                unit: "",
                group: 1,
              },
            ],
            group_count: 1,
          },
        },
        cyProductList: [], // 成药联想数据
      };
    },
    watch: {
      editData: {
        handler(newval, oldval) {
          if (newval) {
            this.submitData.prescription = this.editData;
            console.log(this.submitData);
          }
        },
        immediate: true,
      },
    },
    created() {
      if (this.editData) {
        this.submitData.prescription = this.editData;
      }
    },
    mounted() {
      this.restaurants = this.loadAll();
    },
    methods: {
      submitForm() {
        var boo;
        this.$refs.formName.validate((valid) => {
          if (valid) {
            boo = true
          } else {
            boo = false;
          }
        });
        return boo
      },
      // 将数据传给父组件
      emitData() {
        return this.submitData;
      },
      async cyProHandleSelect(item, index) {
        console.log(item, index);
        let product = await productDetail({default_id: item.id});
        this.submitData.prescription.details[index].own = product.data
          ? true
          : item.Own;
        this.submitData.prescription.details[index].product_id = product.data
          ? product.data.id
          : item.id;
        this.submitData.prescription.details[index].product_name = product.data
          ? product.data.product_name
          : item.product_name;
        this.submitData.prescription.details[index].pack = product.data
          ? product.data.pack
          : item.pack;
        this.submitData.prescription.details[index].unit = product.data
          ? product.data.number_unit
          : item.number_unit;
        this.submitData.prescription.details[index].price = product.data
          ? Number(product.data.price)
          : Number(item.price || 0);
        this.submitData.prescription.details[index].number = 1;
        let price = this.submitData.prescription.details[index].price;
        let num = this.submitData.prescription.details[index].number;
        this.submitData.prescription.details[index].amount = price * num;
      },
      usageHandleSelect(val, index) {
        this.submitData.prescription.details[index].use_way = val;
      },
      medicationRateHandleSelect(val, index) {
        this.submitData.prescription.details[index].medication_rate = val;
      },
      singleUnitHandleSelect(val, index) {
        this.submitData.prescription.details[index].single_unit = val;
      },
      numberUnitHandleSelect(val, index) {
        this.submitData.prescription.details[index].unit = val;
      },
      // 成药产品联想
      async cyQuerySearch(queryString, cb) {
        let pro = await productSearch({
          prefix: queryString,
          size: 10,
          condition: {
            category_id: "2",
          },
        });
        this.cyProductList = pro.data.ElasticProduct || [];
        var results = this.cyProductList;
        cb(results);
      },
      // 成药处方改变---改变更新状态
      cyChange(val, index, type) {
        if (type == "product") {
          this.submitData.prescription.details[index].stock = 0;
          this.submitData.prescription.details[index].own = false;
          this.submitData.prescription.details[index].product_id = 0;
          this.submitData.prescription.details[index].production = "";
          this.submitData.prescription.details[index].pack = "";
          this.submitData.prescription.details[index].use_way = "";
          this.submitData.prescription.details[index].medication_rate = "";
          this.submitData.prescription.details[index].single_dose = "";
          this.submitData.prescription.details[index].single_unit = "";
          this.submitData.prescription.details[index].unit = "";
          this.submitData.prescription.details[index].price = 0;
          this.submitData.prescription.details[index].number = "";
          this.submitData.prescription.details[index].amount = 0;
        }else if(this.submitData.prescription.details[index].stock<=0){
          this.submitData.prescription.details[index].own = false
          this.submitData.prescription.details[index].price = 0
        }
        if (this.submitData.prescription.details[index].update_status !== 2) {
          this.submitData.prescription.details[index].update_status = 1;
        }
      },
      // 用法输入联想--开始
      cyyfQuerySearch(queryString, cb) {
        console.log(111)
        var restaurants = this.remindData.xy_usage;
        var results = queryString
          ? restaurants.filter(this.commonCreateFilter(queryString))
          : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      commonCreateFilter(queryString) {
        return (restaurant) => {
          return (
            restaurant.toLowerCase().indexOf(queryString.toLowerCase()) === 0
          );
        };
      },
      // 用药频率输入联想--开始
      medicationRateQuerySearch(queryString, cb) {
        var restaurants = this.remindData.eat_rate;
        var results = queryString
          ? restaurants.filter(this.commonCreateFilter(queryString))
          : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      // 剂量单位输入联想--开始
      singleUnitQuerySearch(queryString, cb) {
        var restaurants = this.remindData.dose_unit;
        var results = queryString
          ? restaurants.filter(this.commonCreateFilter(queryString))
          : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      // 销售单位输入联想--开始
      numberUnitQuerySearch(queryString, cb) {
        var restaurants = this.remindData.number_unit;
        var results = queryString
          ? restaurants.filter(this.commonCreateFilter(queryString))
          : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      querySearch(queryString, cb) {
        var restaurants = this.restaurants;
        var results = queryString
          ? restaurants.filter(this.createFilter(queryString))
          : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (
            restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
            0
          );
        };
      },
      removePatentItem(item) {
        var index = this.submitData.prescription.details.indexOf(item);
        if (index !== -1) {
          this.submitData.prescription.details.splice(index, 1);
        }
      },
      addPatentItem(index) {
        console.log(index);
        if (
          index == -1 ||
          index == this.submitData.prescription.details.length - 1
        ) {
          this.submitData.prescription.details.push({
            own:true,
            product_id: 0,
            product_name: "",
            pack: "", // 规格
            use_way: "", // 用法
            medication_rate: "", // 用药频率
            single_dose: "", // 用药频率
            single_unit: "", // 单次剂量
            number: "", // 数量
            price: 0, // 价格
            amount: 0, // 总价
            unit: "",
            group: this.submitData.prescription.details.length + 1,
            key: Date.now(),
          });
        }
      },
      handleSelect(item) {
        console.log(item);
      },
      loadAll() {
        return [
          {value: "三全鲜食（北新泾店）", address: "长宁区新渔路144号"},
          {
            value: "Hot honey 首尔炸鸡（仙霞路）",
            address: "上海市长宁区淞虹路661号",
          },
          {
            value: "新旺角茶餐厅",
            address: "上海市普陀区真北路988号创邑金沙谷6号楼113",
          },
          {value: "泷千家(天山西路店)", address: "天山西路438号"},
          {
            value: "胖仙女纸杯蛋糕（上海凌空店）",
            address: "上海市长宁区金钟路968号1幢18号楼一层商铺18-101",
          },
          {value: "贡茶", address: "上海市长宁区金钟路633号"},
          {
            value: "豪大大香鸡排超级奶爸",
            address: "上海市嘉定区曹安公路曹安路1685号",
          },
          {
            value: "茶芝兰（奶茶，手抓饼）",
            address: "上海市普陀区同普路1435号",
          },
          {value: "十二泷町", address: "上海市北翟路1444弄81号B幢-107"},
          {value: "星移浓缩咖啡", address: "上海市嘉定区新郁路817号"},
          {value: "阿姨奶茶/豪大大", address: "嘉定区曹安路1611号"},
          {value: "新麦甜四季甜品炸鸡", address: "嘉定区曹安公路2383弄55号"},
        ];
      },
    },
  };
</script>

<style lang="scss" scoped>
  @import "@/assets/scss/templates/modules/medicinePrescription.scss";
</style>
<style>
  .medicinePrescription-create .el-input__suffix {
    position: absolute;
    height: 100%;
    right: 5px;
    top: 8px;
    text-align: center;
    color: #D23137;
    transition: all 0.3s;
    pointer-events: none;
  }
</style>
